package components

import (
	"os/exec"
	"strings"
)

/****************************************************************

 Manage remote repositories
  remotes                List all configured remotes
  remote-add             Add a new remote repository (by URL)
  remote-modify          Modify properties of a configured remote
  remote-delete          Delete a configured remote
  remote-ls              List contents of a configured remote
  remote-info            Show information about a remote app or runtime


NOTE: https://docs.flatpak.org/en/latest/flatpak-command-reference.html

****************************************************************/

type Remote struct {
	Name   string
	Option string
}

func parseRemote(s string) ([]*Remote, error) {
	// Name          Options
	// flathub       system
	// gnome-nightly system
	// flathub       user

	var remotes []*Remote

	for _, v := range strings.Split(strings.TrimSpace(s), "\n") {
		remotes = append(remotes, &Remote{
			Name:   strings.SplitN(v, "\t", 2)[0],
			Option: strings.SplitN(v, "\t", 2)[1],
		})
	}
	return remotes, nil
}

func RemoteRepos() ([]*Remote, error) {

	cmd := exec.Command("flatpak", "remotes")
	// cmd.Start()
	// cmd.Wait()

	out, err := cmd.Output()
	if err != nil {
		return nil, err
	}

	return parseRemote(string(out))
}
